package day02;

/**
 * 给你一个按照非递减顺序排列的整数数组 nums，和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
 *
 * 如果数组中不存在目标值 target，返回[-1, -1]。
 *
 * 你必须设计并实现时间复杂度为O(log n)的算法解决此问题。
 *
 *
 *
 * 示例 1：
 *
 * 输入：nums = [5,7,7,8,8,10], target = 8
 * 输出：[3,4]
 * 示例2：
 *
 * 输入：nums = [5,7,7,8,8,10], target = 6
 * 输出：[-1,-1]
 * 示例 3：
 *
 * 输入：nums = [], target = 0
 * 输出：[-1,-1]
 *
 *
 */
public class Solution2 {
    public int[] searchRange(int[] nums, int target) {
        int []ans = new int[2];
        ans[0] = leftSearch(nums,target);
        ans[1] = rightSearch(nums,target);
        return ans;
    }
    public int leftSearch(int[] nums,int target){
        if(nums == null||nums.length==0){
            return -1;
        }
        int left = 0,right = nums.length-1;
        while (left+1<right){
            int mid = left + (right-left)/2;
            if(nums[mid]<target){
                left = mid;
            }else{
                right = mid;
            }
        }
        if(nums[left]==target){
            return left;
        }
        if(nums[right]==target){
            return right;
        }
        return -1;
    }
    public int rightSearch(int []nums,int target){
        if(nums == null||nums.length==0){
            return -1;
        }
        int left = 0,right = nums.length-1;
        while (left+1<right){
            int mid = left + (right-left)/2;
            if(nums[mid]<=target){
                left = mid;
            }else{
                right = mid;
            }
        }
        if(nums[right]==target){
            return right;
        }
        if(nums[left]==target){
            return left;
        }
        return -1;
    }
}
